<template>
  <div class="vc-page vc-page-parts">
    <!-- 左侧 - 权限关系集合树 -->
    <el-tree-sider
      tree-title="权限关系集合树"
      :data="permRelTreeData"
      :props="treeProps"
      :default-expanded-keys="defaultExpanded"
      :default-checked-node="defaultChecked"
      :selectable="selectable"
      :node-icon="getNodeIcon"
      :handle-menu="true"
      :menu-events="menuEvents"
      :addable="true"
      @refresh="getPermRelTree"
      @node-click="handleNodeClick"
      @show-menu="showMenu"
      @add="addPermRel"/>

    <!-- 右侧 - 权限列表 -->
    <div class="part-right">
      <!-- 操作按钮 -->
      <div class="vc-btns">
        <el-button size="small" type="primary" class="multi-words" :disabled="!entity.id" @click="relatePerm">关联权限</el-button>
        <el-button size="small" :disabled="selectedIds.length === 0" @click="batchDel">删除</el-button>
      </div>

      <!-- 列表展示 -->
      <div class="vc-table">
        <tables
          v-model="tableConfig.tableData"
          :columns="tableConfig.columns"
          :stripe="true"
          @on-selection-change="handleSelectionChange"/>

        <el-pagination
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="GLOBAL.QUERY.PAGE_SIZE"
          :total="total"
          layout="total, prev, pager, next">
        </el-pagination>
      </div>
    </div>

    <!-- 新增权限关系集合 -->
    <add-perm-rel :dialogVisible="addDialogVisible" @close="closeAddDialog"/>

    <!-- 修改权限关系集合 -->
    <edit-perm-rel :entity="currHandleData" :dialogVisible="editDialogVisible" @close="closeEditDialog"/>

    <!-- 新增权限关系集合项 -->
    <add-ptag :relId="relId" :relName="relName" :dialogVisible="addPtagDialogVisible" @close="closeAddDialog"/>

    <!-- 修改权限关系集合项 -->
    <edit-ptag :entity="currHandleData" :relName="relName" :dialogVisible="editPtagDialogVisible" @close="closeEditDialog"/>

    <!-- 关联权限 -->
    <select-box
      ref="selectBox"
      :allNode="relatePermConfig.allNode"
      :boxDialogVisible="relatePermConfig.editVisible"
      :checkedNode="relatePermConfig.checked"
      :iconConfig="relatePermConfig.iconConfig"
      :rightKeyQ="relatePermConfig.rightKeyQ"
      :searchConfig="relatePermConfig.search"
      :title="relatePermConfig.title"
      @close="relatePermConfig.editVisible = false"
      @save="addAndRemovePermPtag"/>
  </div>
</template>

<script>
import AddPermRel from './addPermRel'
import EditPermRel from './editPermRel'
import AddPtag from './addPtag'
import EditPtag from './editPtag'
import SelectBox from '_c/selectBox'

export default {
  name: 'permRel',
  components: { AddPermRel, EditPermRel, AddPtag, EditPtag, SelectBox },
  data () {
    return {
      // 权限关系集合
      permRelData: [],
      permRelTreeData: null,
      treeProps: {
        id: 'id',
        label: 'text',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      defaultExpanded: [],
      defaultChecked: {},
      selectable: data => {
        return data.type === 'pt'
      },
      getNodeIcon: data => {
        return `vc-icon vc-icon-tree-${data.type === 'pt' ? 'tag' : 'set'}`
      },
      menuEvents: [],
      permRelEvts: [
        {
          name: '新增关系集合',
          event: this.addPermRel
        },
        {
          name: '新增关系集合项',
          event: data => {
            [this.relId, this.relName] = [data.id, data.text]
            this.addPtagDialogVisible = true
          }
        },
        {
          name: '修改关系集合',
          event: data => {
            this.openEditDialog(data, 'editDialogVisible')
          }
        },
        {
          name: '删除关系集合',
          event: data => {
            this.remove(data, 'removePermRel')
          }
        }
      ],
      ptagEvts: [
        {
          name: '修改关系集合项',
          event: data => {
            let rel = this.permRelData.filter(item => item.id === data.pid)
            this.relName = rel.length ? rel[0].text : ''
            this.openEditDialog(data, 'editPtagDialogVisible')
          }
        },
        {
          name: '删除关系集合项',
          event: data => {
            this.remove(data, 'removePermRelPtag')
          }
        }
      ],
      addDialogVisible: false,
      editDialogVisible: false,
      addPtagDialogVisible: false,
      editPtagDialogVisible: false,
      entity: {},
      currHandleData: {},
      relId: '',
      relName: '',
      // 列表
      tableConfig: {
        columns: [
          {
            type: 'selection',
            width: '50'
          },
          {
            title: '序号',
            type: 'index',
            width: '50'
          },
          {
            key: 'code',
            title: '权限编码'
          },
          {
            key: 'name',
            title: '权限名称'
          },
          {
            key: 'descr',
            title: '描述'
          }
        ],
        tableData: []
      },
      currentPage: 1,
      total: 0,
      searchData: {},
      selectedIds: [],
      // 关联权限
      relatePermConfig: {
        iconConfig: {
          parentType: {
            key: 'mgroup',
            icon: 'vc-icon vc-icon-tree-rGroup'
          },
          childrenType: {
            key: 'permission',
            icon: 'vc-icon vc-icon-tree-role'
          }
        },
        rightKey: 'name',
        editVisible: false,
        title: '关联权限',
        listStyle: 'tree',
        search: {
          title: '请输入',
          patch: 'getpermissionByName',
          key: 'name',
          params: {}
        },
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children',
          isLeaf: 'isLeaf'
        },
        allNode: [],
        checked: []
      }
    }
  },
  mounted () {
    this.getPermRelTree()
  },
  methods: {
    /**
     * 获取权限关系集合树
     */
    getPermRelTree () {
      this.entity = {}
      this.$api.getPermRelTree().then(res => {
        if (!res.success || !res.data || !res.data.length) {
          this.permRelTreeData = []
          this.permRelData = []
          this.treeEmptyText = this.GLOBAL.QUERY.EMPTY_TEXT
          this.emptyTableData()
          return
        }
        this.permRelData = res.data
        this.permRelTreeData = this.GLOBAL.array.transToTreeData(res.data)
        let items = this.permRelTreeData.filter(item => item.children && item.children.length);
        [this.defaultExpanded, this.defaultChecked] = items.length ? [[items[0].id], items[0].children[0]] : [[], {}]
      })
    },
    /**
     * 树节点被点击时的回调
     */
    handleNodeClick (data, node) {
      this.entity = Object.assign({}, data.data)
      !node ? this.getPermPage(this.entity.id) : this.handleCurrentChange(1)
    },
    /**
     * 显示右键菜单
     */
    showMenu (data) {
      this.menuEvents = data.type === 'pr' ? this.permRelEvts : this.ptagEvts
    },
    /**
     * '新增'关系集合
     */
    addPermRel () {
      this.addDialogVisible = true
    },
    /**
     * 获取右侧权限列表数据
     */
    getPermPage (id, pageNum = this.currentPage, pageSize = this.GLOBAL.QUERY.PAGE_SIZE, entity = this.searchData) {
      this.$api.getPermPage({
        data: {
          id: id,
          pageNum: pageNum,
          pageSize: pageSize,
          params: Object.assign(entity)
        }
      }).then(res => {
        if (!res.success || !res.data.total) {
          this.emptyTableData()
          return
        }
        if (!res.data.records || !res.data.records.length) {
          this.currentPage--
          this.getPermPage(id)
          return
        }
        this.tableConfig.tableData = res.data.records
        this.total = res.data.total
        this.currentPage = res.data.current
      }).catch(() => {
        this.emptyTableData()
      })
    },
    /**
     * 清空表格数据
     */
    emptyTableData () {
      this.tableConfig.tableData = []
      this.total = 0
      this.currentPage = 1
    },
    /**
     * 点击页数
     */
    handleCurrentChange (val) {
      this.getPermPage(this.entity.id, val)
    },
    /**
     * '新增'弹出框关闭事件
     */
    closeAddDialog (val) {
      this.addDialogVisible = false
      this.addPtagDialogVisible = false
      if (!val) return
      this.getPermRelTree()
    },
    /**
     * '修改'按钮点击事件
     */
    openEditDialog (data, dialog) {
      this.currHandleData = data.data
      this[dialog] = true
    },
    /**
     * '修改'弹出框关闭事件
     */
    closeEditDialog (val) {
      this.editDialogVisible = false
      this.editPtagDialogVisible = false
      if (!val) return
      this.getPermRelTree()
    },
    /**
     * '删除'按钮点击事件
     */
    remove (data, api) {
      this.currHandleData = data.data
      this.api = api
      this.$confirmBox(this.handleRemove)
    },
    /**
     * 删除
     */
    handleRemove () {
      this.$api[this.api]({
        data: [this.currHandleData.id]
      }).then(res => {
        this.getPermRelTree()
        res.success && this.$notifyBox('删除成功', 'success')
      })
    },
    /**
     * 复选框勾选
     */
    handleSelectionChange (val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'id')
    },
    /**
     * '删除'按钮点击事件
     */
    batchDel () {
      this.$confirmBox(this.handleDel)
    },
    /**
     * 删除
     */
    handleDel () {
      this.$api.addAndRemovePermPtag({
        data: {
          add: [],
          remove: this.selectedIds,
          ptagId: this.entity.id
        }
      }).then(res => {
        this.getPermPage(this.entity.id)
        res.success && this.$notifyBox('删除成功', 'success')
      })
    },
    /**
     * '关联权限'按钮点击事件
     */
    relatePerm () {
      this.$api.getMGroupTreeCurr().then(res => {
        if (!res.success) {
          return
        }
        res.data = res.data || []
        res.data.forEach(item => {
          item = Object.assign(item, item.data)
        })
        this.relatePermConfig.allNode = res.data
        this.$api.findPermsByPtagId({
          data: {
            ptagId: this.entity.id
          }
        }).then(res => {
          if (!res.success) {
            return
          }
          this.relatePermConfig.checked = res.data || []
          this.relatePermConfig.editVisible = true
        })
      })
    },
    /**
     * '关联权限'弹出框关闭事件
     */
    addAndRemovePermPtag (add, remove) {
      this.$api.addAndRemovePermPtag({
        data: {
          add: add,
          remove: remove,
          ptagId: this.entity.id
        }
      }).then(res => {
        if (res.success) {
          this.getPermPage(this.entity.id)
          this.relatePermConfig.editVisible = false
          this.$notifyBox('关联权限成功', 'success')
          return
        }
        this.$refs.selectBox.closeDisabled()
      }).catch(err => {
        this.$refs.selectBox.closeDisabled()
      })
    }
  }
}
</script>
